package com.example.shushiyunsst.fragment.main.wallet.sub

import android.content.BroadcastReceiver
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import com.alibaba.fastjson.JSON
import com.example.library_common.base.LazyFragment
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_BALANCE_INFO
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.scan.ScanFrameFragment
import com.example.shushiyunsst.scan.ScanResListener
import com.example.shushiyunsst.util.PayingPassWordVerifyPop
import com.example.wallet.bean.BalanceInfoBean
import com.example.wallet.db.BalanceInfoManager
import com.example.wallet.db.UserInfoManager
import com.example.wallet.global.AppGlobals
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.senon.modularapp.util.JssSpannableString
import java.math.BigDecimal

/**
 * 转账
 * */
class TransferFragment : LazyFragment(), View.OnClickListener {

    companion object {
        fun newInstance(address: String): TransferFragment {
            val args = Bundle()
            args.putString("address", address)
            val fragment = TransferFragment()
            fragment.arguments = args
            return fragment
        }

        fun newInstance(): TransferFragment {
            val args = Bundle()
            val fragment = TransferFragment()
            fragment.arguments = args
            return fragment
        }
    }


    private var address: String = ""

    private var moneyType = AppGlobals.getApplication().getString(R.string.wallet_sst)

    private lateinit var feedingTv: TextView

    private lateinit var moneyTv: TextView

    private lateinit var addressTv: EditText;

    private lateinit var availableCount: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false
        address = arguments?.getString("address", "") ?: ""
    }

    override fun getLayoutId() = R.layout.transfer_layout_fragment

    override fun lazyInit() {
        val balanceInfoBean = BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()
        if (balanceInfoBean == null) {
            getUserBalanceInfo(_mActivity)
            return
        }
        presentBalanceInfo(balanceInfoBean)

    }

    private fun presentBalanceInfo(balanceInfoBean: BalanceInfoBean?) {
        val feeBeanBean = BalanceInfoManager.mBalanceInfoManager.getFeeBeanBean()
        val minerFees = feeBeanBean?.sst
        val availableValue = balanceInfoBean?.totalBalance?.toString()
        val span = JssSpannableString(
            _mActivity,
            "可用${availableValue}$moneyType , 矿工费: $minerFees$moneyType"
        )
            .first(availableValue.toString()).textColor(R.color.PrimaryColor)
            .first(minerFees.toString()).textColor(R.color.PrimaryColor)


        feedingTv.text = span
    }

    override fun handMessage(msg: MessageWrap?) {

        if (msg?.message == TO_REFRESH_BALANCE_INFO) {
            val balanceInfoBean = BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()
            presentBalanceInfo(balanceInfoBean)
        }
    }

    override fun initView(view: View) {

        feedingTv = view.findViewById(R.id.feedingTv)

        addressTv = view.findViewById(R.id.addressTv)

        addressTv.setText(address)

        availableCount = view.findViewById(R.id.availableCount)

        moneyTv = view.findViewById(R.id.moneyTv)

        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        moneyTv.text = moneyType

        loadRootFragment(R.id.wallet_header, WalletHeadFragment.newInstance())

        view.findViewById<View>(R.id.mSaner)
            .setOnClickListener {
                val newInstance = ScanFrameFragment.newInstance()
                newInstance.setScanResListener(object : ScanResListener {
                    override fun onResStr(resStr: String) {
                        Toast.makeText(_mActivity, resStr, Toast.LENGTH_SHORT).show()
                    }
                })
                start(newInstance)
            }


        view.findViewById<View>(R.id.sureTv).setOnClickListener(this)

        view.findViewById<View>(R.id.mSaner).setOnClickListener(this)

        view.findViewById<View>(R.id.forAll).setOnClickListener(this)

    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.forAll -> {
                val balanceInfoBean = BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()
                availableCount.setText(balanceInfoBean?.totalBalance.toString())
            }

            R.id.mSaner -> {
                val newInstance = ScanFrameFragment.newInstance()
                newInstance.setScanResListener(object : ScanResListener {
                    override fun onResStr(resStr: String) {
                        addressTv.setText(resStr)
                    }
                })
//                supportDelegate.start(newInstance)
                start(newInstance)
            }
            R.id.sureTv -> {
                if (!checkInfo()) {
                    return
                }
                val mPop = PayingPassWordVerifyPop(_mActivity)
                XPopup.Builder(_mActivity)
                    .setPopupCallback(object : SimpleCallback() {
                        override fun onDismiss(popupView: BasePopupView?) {
                            super.onDismiss(popupView)
                            if (mPop.getIsOnVerifyPop()) {
                                if (mPop.getVerifyPop()) {
                                    sendAll()
                                } else {
                                    Toast.makeText(_mActivity, "支付密码错误", Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    })
                    .asCustom(mPop)
                    .show()

            }
        }
    }

    private fun checkInfo(): Boolean {
        var flag = true
        val toAddr = addressTv.text.toString()
        val txNums = availableCount.text.toString()
        if (toAddr.isNullOrBlank()) {
            Toast.makeText(_mActivity, "请输入转账地址", Toast.LENGTH_SHORT).show()
            flag = false
        }

        if (txNums.isNullOrBlank()) {
            Toast.makeText(_mActivity, "请输入转账地址数量", Toast.LENGTH_SHORT).show()
            flag = false
        }

        return flag
    }

    private fun sendAll() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val toAddr = addressTv.text.toString()
        val txNums = availableCount.text.toString()
        val map = mapOf(
            "fromAddr" to userInfo?.sysWalletAddress,
            "toAddr" to toAddr,
            "txNums" to txNums
        )
        RestClient.builder()
            .url(R.string.transferSST)
            .raw(JSON.toJSONString(map))
            .success {
                Toast.makeText(_mActivity, "转账成功", Toast.LENGTH_SHORT).show()
                getUserBalanceInfo(_mActivity)
                onBackPressedSupport()
            }
            .failure {
                Toast.makeText(_mActivity, "转账失败", Toast.LENGTH_SHORT).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }.build().post()
    }
}